package com.zhangjinghao.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.zhangjinghao.entity.City;
import com.zhangjinghao.entity.Food;
import com.zhangjinghao.entity.SelectArg;
import com.zhangjinghao.entity.Vender;
import com.zhangjinghao.es.FoodRepository;
import com.zhangjinghao.mapper.CityMapper;
import com.zhangjinghao.mapper.VenderMapper;
import com.zhangjinghao.service.CityService;
import com.zhangjinghao.service.FoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("food")
public class FoodController {

    @Autowired
    private FoodService foodService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CityService cityService;
    @Autowired
    private VenderMapper venderMapper;
//    @Autowired
//    private KafkaTemplate kafkaTemplate;

    /**
     * 跳转列表
     * @param selectArg
     * @return
     */
    @RequestMapping("list")
    public String list(SelectArg selectArg){

        PageInfo<Food> pageInfo = null;
        //页面预热
        if (redisTemplate.hasKey("page-1")){
            pageInfo = (PageInfo<Food>) redisTemplate.opsForValue().get("page-1");
        }else{
            pageInfo = foodService.pageInfo(new SelectArg(1));
            redisTemplate.opsForValue().set("page-1",pageInfo,new Random().nextInt(1000)+1000, TimeUnit.MINUTES);
        }
        //  页面缓存 防止页面为负数的恶意攻击
        if (selectArg.isEmpty() && selectArg.getPageNum()!=1 && selectArg.getPageNum()>0){
            if (redisTemplate.hasKey("page-"+selectArg.getPageNum().toString())){
                pageInfo = (PageInfo<Food>) redisTemplate.opsForValue().get("page-"+selectArg.getPageNum().toString());
            }else{
                pageInfo = foodService.pageInfo(selectArg);
                redisTemplate.opsForValue().set("page-"+selectArg.getPageNum().toString(),pageInfo,new Random().nextInt(1000)+1000, TimeUnit.MINUTES);
            }
        }else{
            //判断有查询，而不是单纯的第一页
            if (!selectArg.isEmpty()){
                //有查询
                if (redisTemplate.hasKey("cooling")){
                    //获取上一次的页面
                    pageInfo = (PageInfo<Food>) redisTemplate.opsForValue().get("page-last");
                    request.setAttribute("warning",JSON.toJSON("每五秒只能查询一次"));
                }else{
                    pageInfo = foodService.pageInfo(selectArg);
                    redisTemplate.opsForValue().set("cooling","",10, TimeUnit.SECONDS);
                    request.setAttribute("warning",JSON.toJSON(null));
                }
            }
        }

        //存入上一次获取的页面
        redisTemplate.opsForValue().set("page-last",pageInfo,new Random().nextInt(1000)+1000, TimeUnit.MINUTES);

        request.setAttribute("list",pageInfo);
        request.setAttribute("arg",selectArg);

        return "list";
    }

    /**
     * 前往添加/修改
     * @param
     * @return
     */
    @RequestMapping("toInsert")
    public String insert(Food food){
        System.out.println(food);
        //  缓存获取三级联动
        List<City> cities = null;
        if (redisTemplate.hasKey("linkage3")){
            cities = (List<City>)redisTemplate.opsForValue().get("linkage3");
        }else{
            cities = cityService.selectCity(0);
            redisTemplate.opsForValue().set("linkage3",cities,new Random().nextInt(1000)+1000, TimeUnit.MINUTES);
        }
        //  缓存厂家
        List<Vender> venders = null;
        if (redisTemplate.hasKey("venders")){
            venders = (List<Vender>)redisTemplate.opsForValue().get("venders");
        }else{
            venders = venderMapper.selectList();
            redisTemplate.opsForValue().set("venders",venders,new Random().nextInt(1000)+1000, TimeUnit.MINUTES);
        }

        //  设置flag
        redisTemplate.opsForValue().set("flag","",new Random().nextInt(1000)+1000, TimeUnit.MINUTES);

        request.getSession().setAttribute("CITYS", JSON.toJSON(cities));
        request.getSession().setAttribute("VENDERS",JSON.toJSON(venders));

        //如果是执行修改
        if (food.getId() != null){
            request.setAttribute("diet",foodService.selectById(food.getId()));
        }else{
            request.setAttribute("diet",food);
        }


        return "insert";
    }

    /**
     * 执行添加/修改
     * @param food
     * @param result
     * @return
     */
    @RequestMapping("insert")
    public String  insert(@Valid @ModelAttribute("diet") Food food, BindingResult result){
        if (result.hasErrors()){
            return "insert";
        }
        if (!redisTemplate.hasKey("flag")){
            result.rejectValue("message",null,"请勿重复提交");
            return "insert";
        }
        //做日期处理
        Calendar instance = Calendar.getInstance();
        instance.setTime(food.getCreateDate());
        instance.add(Calendar.DATE,food.getExpirationNum());
        food.setExpirationDate(instance.getTime());
        if (food.getId()==null){
            if (foodService.insert(food)>0){
//                kafkaTemplate.send("test","insert",food);
                return "redirect:list";
            }else{
                result.rejectValue("message",null,"信息故障");
                return "insert";
            }
        }else{
            //修改
            if (foodService.update(food)>0){
//                kafkaTemplate.send("test","update",food);
                return "redirect:list";
            }else{
                result.rejectValue("message",null,"信息故障");
                return "insert";
            }
        }
    }

    /**
     * 执行删除
     * @param ids
     * @return
     */
    @RequestMapping("delete")
    @ResponseBody
    public int delete(String ids){

        return foodService.delete(ids);
    }
}
